import time
import csv
import json
import re
from os import system

from playwright.sync_api import sync_playwright


def handle_json(json):
    csvFile = open("./data/storeC_20230202.csv", 'a', encoding='utf-8', newline='')
    try:
        writer = csv.writer(csvFile)
        results = json['data']['list']
        # print(results)
        for i in range(0, len(results)):
            data_list = json['data']['list'][i]
            # print(data_list)
            # print(data_list['f0'])
            # print(data_list['f1'])
            # print(data_list['f2'])
            writer.writerow((data_list['f0'], data_list['f1'], data_list['f2']))
    finally:
        csvFile.close()


def on_response(response):
    # print(response)
    if '/datasearch/data/nmpadata/search' in response.url and response.status == 200:
        handle_json(response.json())


def run():
    with sync_playwright() as p:
        for browser_type in [p.firefox]:
            # 列表末尾加百度防止监听报错
            browser = browser_type.launch(headless=False)
            # page = browser.new_page()
            context = browser.new_context()
            page = context.new_page()
            # page.on('response', on_response)
            page.goto('https://www.nmpa.gov.cn/datasearch/search-result.html')
            # time.sleep(10)
            page.locator("text=关闭").click()

            # Click [placeholder="请选择"]
            page.locator("[placeholder=\"请选择\"]").click()

            # Click text=药品经营企业 >> nth=0
            page.fill('//*[@id="home"]/main/div[1]/div[7]/div/div[2]/input', '苏CA')
            page.locator("text=药品经营企业").first.click()
            # time.sleep(2)
            page.wait_for_timeout(2000)
            page.click('//*[@id="home"]/main/div[1]/div[7]/div/div[2]/div/button')
            # time.sleep(2)
            # page.wait_for_timeout(2000)
            with context.expect_page() as new_page_info:
                register_page = new_page_info.value
                #  cancel_request(route, request):
                #    route.abort()
                # register_page.route(re.compile(r"(\.png)|(\.jpg)"), cancel_request)
                register_page.wait_for_load_state()
                # print(register_page.title())
                register_page.wait_for_timeout(5000)
                register_page.locator("text=关闭").click()
                register_page.on('response', on_response)
                register_page.wait_for_timeout(2000)
                # 设置每页展示条数
                register_page.click('//*[@id="home"]/div[3]/div[3]/div/div/span[2]/div/div/input')
                register_page.locator("text=20条/页").first.click()

                # region 定位遍历的坐标
                hello = open("./data/storeC.csv", 'r', encoding='utf-8')
                # con = hello.readline()
                strLine = hello.readline().split(',')
                print(strLine)
                con = strLine[0]
                countStr = int(strLine[1])
                print(con)
                hello.close()
                # 终止检测任务
                if con == 'end':
                    system('taskkill /F /IM cmd.exe')
                list = storeList[storeList.index(con) + 0:]

                # endregion 定位遍历的坐标
                print(list)
                print(storeList)
                # 输入筛选条件
                for item in list:
                    # 终止检测任务
                    if item == 'end':
                        system('taskkill /F /IM cmd.exe')

                    register_page.fill('//*[@id="home"]/div[3]/div[1]/div[1]/div[2]/div/input', item)
                    register_page.click('//*[@id="home"]/div[3]/div[1]/div[1]/div[2]/div/div/button')
                    # time.sleep(5)
                    # pageStr = register_page.query_selector('span.el-pagination__total').text_content()
                    # pageCount = int(pageStr.split(' ', 2)[1])
                    # print(pageCount)
                    count = countStr

                    # region 跳转到指定页码
                    register_page.wait_for_timeout(3000)
                    register_page.fill('//*[@id="home"]/div[3]/div[3]/div/div/span[3]/div/input', str(count))
                    register_page.keyboard.press("Enter")
                    register_page.wait_for_timeout(1000)
                    # endregion 跳转到指定页码

                    while True:
                        # region 记录当前节点及页码
                        with open("./data/storeC.csv", 'w', encoding='utf-8') as hello:
                            hello.write(item+","+str(count))
                        print(item + "第" + str(count) + "页")
                        # endregion 记录当前节点及页码

                        register_page.wait_for_timeout(6000)  # 设置成 4 秒就不够稳定了，也许可以再等待长一点
                        register_page.wait_for_load_state('networkidle')
                        # time.sleep(5)
                        # btn = register_page.query_selector('button.btn-next')
                        flag = register_page.query_selector('button.btn-next').get_attribute('disabled')
                        count = count + 1
                        if flag is None:
                            register_page.click('button.btn-next')
                            # register_page.click('//*[@id="home"]/div[3]/div[3]/div/button[2]')
                            register_page.wait_for_load_state('networkidle')
                        else:
                            countStr = 1
                            break
            # time.sleep(2)
            page.wait_for_timeout(2000)
            browser.close()


def init():
    global storeList
    list = ['粤CB0', '粤CB1', '粤CB2', '粤CB6', '粤CB750', '粤CB751', '粤CB752', '粤CB753', '粤CB754',
            '粤CB755', '粤CB756', '粤CB757', '粤CB758', '粤CB759', '粤CB76', '粤CD', '川CA0', '川CA3', '川CA8', '川CB ',
            '川CB0', '川CB1', '川CB2', '川CB3', '川CB5', '川CB9', '川CB812', '川CB813', '川CB816', '川CB817', '川CB818',
            '川CB82', '川CB83', '川CB87']
    # '冀CA', '冀CB（', '冀CB(', '冀CB0', '冀CB1', '冀CB11', '冀CB13', '冀CB17', '冀CB2','滇CB', '辽CA',
    # '冀CB3', '冀CB5', '冀CB6', '冀CD','鲁CB532',
    #             '豫CB2', '豫CB32', '豫CB33', '豫CB34', '豫CB36', '豫CB371', '豫CB372', '豫CB370', '豫CB373', '豫CB34', '豫CB375',
    #             '豫CB376', '豫CB377', '豫CB38', '豫CB379', '豫CB39', '豫CB7', '豫CB9', '滇CA','辽CB0', '辽CB1',
    # '辽CB41', '辽CB42', '辽CB43', '黑CA', '黑CB', '湘CA73', '湘CA74', '湘CA74','湘CB', '皖CA', '皖CB-', '皖CB0', '皖CB1',
    #             '皖CB55', '皖CB56','鲁CA','鲁CB  ','鲁CB0','鲁CB1','鲁CB2','鲁CB3','鲁CB50','鲁CB51','鲁CB52','鲁CB530','鲁CB531',
    # '鲁CB533','鲁CB534',
    # '吉B', '苏B', '浙B', '冀B', '豫B', '滇B', '辽B', '黑B', '湘B', '皖B', '鲁B', '赣B', '鄂B', '甘B', '晋B', '陕B',
    #             '闽B', '黔B', '粤B', '川B', '青B', '藏B', '琼B', '新B', '桂B', '宁B', '蒙B', '藏B', '京B', '津B', '沪B',
    # '鲁CB535','鲁CB536','鲁CB537','鲁CB538','鲁CB539','鲁CB54','鲁CB59','鲁CD',
    #             '苏CA','粤CA','粤CB ',
    # '冀A'

    storeList = ['冀CA', '冀CB', '冀CD',
                 '豫CA', '豫CB1', '豫CB2', '豫CB32', '豫CB33', '豫CB34', '豫CB36', '豫CB370', '豫CB371', '豫CB372', '豫CB373',
                 '豫CB374', '豫CB375', '豫CB376', '豫CB377', '豫CB378', '豫CB379', '豫CB39', '豫CB7', '豫CB9', '豫CD',
                 '滇CA', '滇CB', '滇CD',
                 '黑CA', '黑CB0', '黑CB45', '黑CB46',
                 '湘CA73', '湘CA74', '湘CA75', '湘CB',
                 '皖CA', '皖CB0', '皖CB1', '皖CB55', '皖CB56', '皖CD',
                 '鲁CA', '鲁CB0', '鲁CB1', '鲁CB2', '鲁CB3', '鲁CB50', '鲁CB51', '鲁CB52',
                 '鲁CB530', '鲁CB531', '鲁CB532', '鲁CB533', '鲁CB534', '鲁CB535', '鲁CB536', '鲁CB537', '鲁CB538', '鲁CB539',
                 '鲁CB54', '鲁CD',
                 '苏CA', '苏CB0', '苏CB1', '苏CB2', '苏CB510', '苏CB511', '苏CB512', '苏CB513', '苏CB514', '苏CB515', '苏CB516',
                 '苏CB517', '苏CB518', '苏CB519', '苏CB9', '苏CD',
                 '浙CA', '浙CB0', '浙CB1', '浙CB570', '浙CB571', '浙CB572', '浙CB573', '浙CB574', '浙CB575', '浙CB576', '浙CB577',
                 '浙CB578', '浙CB579', '浙CB58',
                 '赣CA', '赣CB',
                 '鄂CA', '鄂CB',
                 '甘CA', '甘CB', '甘CD',
                 '晋CA', '晋CB',
                 '陕CA', '陕CB', '陕CD',
                 '吉CA', '吉CB', '吉CD',
                 '闽CA', '闽CB',
                 '黔CA', '黔CB', '黔CD',
                 '粤CA', '粤CB0', '粤CB1', '粤CB2', '粤CB6', '粤CB750', '粤CB751', '粤CB752', '粤CB753', '粤CB754', '粤CB755',
                 '粤CB756', '粤CB757', '粤CB758', '粤CB759', '粤CB76', '粤CD',
                 '川CA0', '川CA3', '川CA8', '川CB0', '川CB1', '川CB2', '川CB3', '川CB5', '川CB9', '川CB812', '川CB813', '川CB816',
                 '川CB817', '川CB818', '川CB82', '川CB83', '川CB87', '川CD',
                 '青C',
                 '藏C',
                 '琼C',
                 '新C',
                 '桂CA', '桂CB',
                 '宁C',
                 '蒙C',
                 '京C',
                 '津C',
                 '沪C',
                 '渝CA', '渝CB', '渝CD', 'end']


# 按间距中的绿色按钮以运行脚本。
if __name__ == '__main__':
    # a= '共 9990 条'
    # print(a.split(' ',2)[1])
    init()
    run()
